var WSServer = require('ws').Server,
    util = require('util'),
    EventEmitter = require('events').EventEmitter;

var getNextClientId = (function() {
    var clientId = 1;
    return function() {
        return clientId++;
    };    
})();

NetworkManager = function(opts) {
    this._sockets = {};
    opts = opts || {};
    var port = opts.port || 4444;
    var server = new WSServer({port: port});

    this.time = opts.time;
    
    var self = this;
    server.on('connection', function(socket) {
        self.onClientConnected(socket);
    });
    this.server = server;
}

util.inherits(NetworkManager, EventEmitter);

NetworkManager.prototype.onClientConnected = function(socket) {
    var id = getNextClientId();
    this._sockets[id] = socket;

    socket.__jc__id = id;

    var self = this;
        
    socket.on('close', function() {
        delete self._sockets[id];
        self.emit('player_disconnected', {
            clientId: id
        });
    });

    this.emit('player_connected', {
        id: id,
        socket: socket
    });
    

};

NetworkManager.prototype.onClientDisconnected = function() {
    
};

/*
 * Send message to client
 */
NetworkManager.prototype.send = function(clientId, message) {
    var sock = this._sockets(clientId);
    if (!sock) {
        //handle
    }
    var payload = message;
    if (typeof message === 'object') {
        payload = JSON.stringify(message);
    }
    sock.send(payload);
};

/*
 * Broadcast to all clients
 */
NetworkManager.prototype.broadcast = function(message) {
    var payload = message;
    if (typeof message === 'object') {
        payload = JSON.stringify(message);
    }
    var c, ss = this._sockets;
    for (c in ss) {
        if (ss.hasOwnProperty(c)) {
            ss[c].send(payload);
        }    
    }
};



//exports.NetworkManager = NetworkManager;



